<?php

defined('BASEPATH') or die('forbidden');

class Groupstrategy_Controller Extends Controller {

	private $moduleList;	//模块信息
	private $areaList;	//区名信息
	private $modStrategyList;	//模块策略对应表

	function _init() {
		check_level(50, segment(0), segment(1), segment(2, 'index'));
		require_once(CONFIGPATH . 'inc.php');

		//模块名信息
		if (false == $this->getModuleList()) {
			return;
		}

		//区名信息
		if (false == $this->getAreaList()) {
			return;
		}

		//得到模块策略信息
		if (false == $this->getModStrategyList()) {
			return;
		}
	}

	function index() {
		$this->view->display("activity/groupstrategy/index");
	}

	function flexigrid() {
		list($colkey, $colsinfo, $where, $sortname, $sortorder, $offset, $rp, $page) = $this->common->get_flexigrid_params();

		//print_r($colsinfo);

		$rows = array();

		$sql = "SELECT COUNT(id) AS num FROM act_area_strategy WHERE {$where}";
		$one = $this->db->one($sql);
		$total = $one['num'];
		$selectSql="SELECT {$colsinfo} FROM act_area_strategy WHERE {$where}  ORDER BY {$sortname} {$sortorder}  LIMIT {$offset},{$rp}";
		//echo " sql = $selectSql ";
		$this->db->query($selectSql);
		while ($n = $this->db->get_array('default')) {
			$n['starttime'] = date('Y-m-d H:i:s', $n['starttime']);
			$n['endtime'] = date('Y-m-d H:i:s', $n['endtime']);
			$rows[] = array('id' => $n['id'], 'cell' => $n);
		}
		//print_r($rows);
		$result = array(
            'page' => $page,
            'total' => $total,
            'rows' => $rows
		);
		echo json_encode($result);
	}

	function add($id = 0) {
		if (is_submit()) {
			//默认是30秒后无法响应，在此修改下时间为无限长
			set_time_limit(0);

			$data = $_POST['row'];
			$areaIds = $_POST['areaIds'];

			//print_r($areaIds);
			//print_r($data);
			//print_r($data['module']);
			//cp_tips('success', $rowdata['groupname']);
			//print_r($area_id);

			//时间转成uniux时间
			$data['starttime'] = strtotime($data['starttime']);
			$data['endtime'] = strtotime($data['endtime']);
			//print_r($data);
			$errorArea = array();	//错误区
			$rightArea = array();	//正确区
			$sendJson = array();	//发送给服务器的json数据
			$sendSuccessData = array();	//要插入到数据库中的数据

			foreach ($data['module'] as $key => $value)
			{
				//echo " key = $key ";
				//print_r($value);

				unset($jsonData);
				$jsonData = array();

				//print_r($data);

				$jsonData['tableenum'] = (string)$value['tableenum'];
				$jsonData['tablename'] = (string) $this->moduleList[$value['tableenum']]['tablename'];
				$jsonData['tabledes'] = (string) $this->moduleList[$value['tableenum']]['des'];
				$jsonData['strategyid'] = (string)$value['strategyid'];
				$jsonData['des'] = (string)$value['des'];
				$jsonData['starttime'] = (string)$data['starttime'];
				$jsonData['endtime'] = (string)$data['endtime'];

				//print_r($jsonData);
				$sendJson[] = $jsonData;
			}

			foreach ($areaIds as $key => $value)
			{
				//echo " area key:$key value:$value ";
				if (0 == $value)
				{	//代表全部区号
					continue;
				}
					
				$url = $this->areaList[$value]['host']."action=52&json_str=".json_encode($sendJson);

				//echo " url = $url ";
				$strResultStr = vpost($url);
				if ($strResultStr != '0' || $strResultStr === FALSE) {
					//发送失败。。。。
					$errorArea[] = $value;

					//echo " error url = $url";
					//echo " error send area: $value ";
				}else
				{
					//发送成功
					foreach ($sendJson as $subkey=>$subvalue)
					{
						//下面几个字段是内部需要使用的
						$subvalue['areaid'] = (string)$value;
						$subvalue['areaname'] = (string)$this->areaList[$value]['name'];
						$subvalue['strategyname'] = (string)$this->modStrategyList[$subvalue['tableenum']][$subvalue['strategyid']];
						$sendSuccessData[] = $subvalue;
					}
					//echo " success send area: $key ";
					$rightArea[] = $value;
				}
			}

			//print_r($errorArea);
			//print_r($rightArea);

			$activityId = 0;

			if(0 < count($rightArea))
			{
				echo " send success area:";
				foreach ($rightArea as $key => $value)
				{
					echo " $value, ";
				}
			}
			if(0 < count($errorArea))
			{
				echo " send error area:";
				foreach ($errorArea as $key => $value)
				{
					echo " $value, ";
				}
			}
			//只有正确的活动才插入到数据库中去
			foreach ($sendSuccessData as $key => $value)
			{
				//先删除下数据库中的重复数据
				if (false != $this->db->delete("act_area_strategy", array('areaid'=>$value['areaid'],'tableenum'=>$value['tableenum']))) {
					;
				}

				//增加一个活动id字段
				$value['activityid'] = $activityId;
				if(false != $this->db->insert('act_area_strategy', $value,true))
				{
				}else
				{
					//echo " $value[areaid], ";
				}
			}
		}else
		{
			set_area_list_view("arealist");
			$this->view->assign('modStrategyList',$this->modStrategyList);
			$this->view->assign("moduleList",$this->moduleList);
			$this->view->display("activity/groupstrategy/add");
		}
	}

	function edit($id) {
		if (!$id)
		{
			error(translate('C_INVALID_PARAM_ID', $id));
		}
		$row = $this->db->one("SELECT * FROM act_area_strategy WHERE id={$id}");
		if (!is_array($row))
		{
			error(translate('C_INVALID_PARAM_ID', $id));
		}
		if (is_submit())
		{
			$rowdata = $_POST['row'];
			//print_r($rowdata);

			//先发信息
			$jsonData = array();

			$jsonData['tableenum'] = (string)$rowdata['tableenum'];
			$jsonData['tablename'] = (string)$this->moduleList[$rowdata['tableenum']]['tablename'];
			$jsonData['strategyid'] = (string)$rowdata['strategyid'];
			$jsonData['des'] = (string)$rowdata['des'];
			$jsonData['starttime'] = (string)(strtotime($rowdata['starttime']));
			$jsonData['endtime'] = (string)(strtotime($rowdata['endtime']));

			$sendJson = array();
			$sendJson[]=$jsonData;

			$url = $this->areaList[$rowdata['areaid']]['host']."action=52&json_str=".json_encode($sendJson);
			//echo "url = $url";
			$ret = vpost($url);
			
			if (0 != $ret) {
				echo " edit error";
			}else
			{
				echo "area num:".$rowdata['areaid']." send success ";
				//cp_tips("success");

				//再把数据插入到数据库中去
				$insertData = array();
				$insertData['strategyid'] = $rowdata['strategyid'];
				$insertData['strategyname'] = $this->modStrategyList[$rowdata['tableenum']][$rowdata['strategyid']];
				$insertData['des'] = $rowdata['des'];
				$insertData['starttime'] = strtotime($rowdata['starttime']);
				$insertData['endtime'] = strtotime($rowdata['endtime']);

				//print_r($data);
				$result = $this->db->update("act_area_strategy", $insertData, array("id"=>$id));
			}

		}else
		{
			//不是提交信息，就显示页面
			$row=$this->db->one("select * from act_area_strategy where id=$id ");

			$this->view->assign("modStrategyList",$this->modStrategyList);
			$this->view->display("activity/groupstrategy/edit", array('row' => $row));
		}

	}

	function del($autoid) {
			
		$c = 0;
		$r = '';
		//先查下是不是有效的id
		$rowdata = $this->db->one("SELECT * FROM act_area_strategy WHERE id={$autoid}");
		if (!is_array($rowdata))
		{
			error(translate('C_INVALID_PARAM_ID', $id));
		}
		
		//向服务器发送删除消息
		//先发信息
		$jsonData = array();
		
		$jsonData['tableenum'] = (string)$rowdata['tableenum'];
		$jsonData['tablename'] = (string)$this->moduleList[$rowdata['tableenum']]['tablename'];
		$jsonData['strategyid'] = (string)$rowdata['strategyid'];
		$jsonData['des'] = (string)$rowdata['des'];
		$jsonData['starttime'] = (string)(time());
		$jsonData['endtime'] = (string)(time());
		
		$sendJson = array();
		$sendJson[]=$jsonData;
		
		$url = $this->areaList[$rowdata['areaid']]['host']."action=52&json_str=".json_encode($sendJson);
		//echo "url = $url";
		$ret = vpost($url);
		if (0 != $ret) {
			error(translate('C_INVALID_PARAM_ID', $id));
			return;
		}
		
		//删除数据		
		if ($this->db->delete('act_area_strategy', array('id' => $autoid))) {
			insert_log(translate('MENU_ACTIVITY_GROUPSTRATEGY'),translate('DEL'), array('id'=> $autoid));
			$c = 1;
			$r = translate('C_TIPS_SUCCESS_TEXT');
		} else {
			$r = translate('C_TIPS_ERROR_TEXT');
		}
		json_output($c, $r);

	}

	function multi() {
		//print_r($_POST);
		 $type = $this->input->post("type");
		 $ids = $this->input->post("ids");
		 $c = 0;
		 $r = '';
		 //echo " type = $type ";
		 //echo " ids = $ids ";
		 if (count(explode(',', $ids)) == 0) {
		 	$r = translate('C_INVALID_PARAMS');
		 } else 
		 {
			 if ($type == 'delete') {
				 $sql = "DELETE FROM act_area_strategy WHERE id IN ({$ids})";
	            //echo " sql = $sql ";
	            $this->db->query($sql);
				 $c = 1;
			 } else 
			 {
			 	$r = translate('C_INVALID_PARAMS');
			 }
		 }
		 json_output($c, $r);
		 
	}

	//得到模块策略信息
	function getModStrategyList()
	{
			
		foreach ($this->moduleList as $key => $value)
		{
			//$key是tableenum
			$sql = "SELECT *  FROM  ".$value['tablename'];
			$this->db->query($sql);
			//$number = 0;
			while ($n = $this->db->get_array('default'))
			{
				//$key 是tableenum
				$this->modStrategyList[$key][$n['strategyid']] = $n['strategyname'];
				//++$number;
			}

			if(0 == count($this->modStrategyList))
			{
				echo "<script>alert( tablename ".$value['tablename']." '" . translate('C_CREATE_TABLENAME') . "');</script>";
				return false;
			}
		}
			
		return true;
	}

	//得到分区信息
	function getAreaList()
	{
		$sql = "SELECT *  FROM {pre}areasample ";
		$this->db->query($sql);
		//echo "sql:$sql";
		while ($n = $this->db->get_array('default'))
		{
			//print_r($n);
			$this->areaList[$n['id']]['name']=$n['name'];
			$this->areaList[$n['id']]['host']=$n['host'];
		}
		//print_r($this->strategyList);
		if(0 == count($this->areaList))
		{
			echo "<script>alert('" . translate('C_ADD_AREA') . "');</script>";
			return false;
		}
		return true;
	}

	//得到模块信息
	function getModuleList()
	{
		$sql = "SELECT *  FROM act_module ";
		$this->db->query($sql);
		while ($n = $this->db->get_array('default'))
		{
			$this->moduleList[$n['tableenum']]['des']=$n['des'];
			$this->moduleList[$n['tableenum']]['tablename']=$n['tablename'];
			$this->moduleList[$n['tableenum']]['tableenum']=$n['tableenum'];
		}

		if(0 == count($this->moduleList))
		{
			echo "<script>alert('" . translate('C_CREATE_TABLENAME') . "');</script>";
			return false;
		}
		return true;
	}

	//adajx技术返回给页面
	function getStrategyId()
	{
		$tableenum = $_GET['tableenum'];
		foreach ($this->modStrategyList[$tableenum] as $key => $value)
		{
			echo "<option value=".$key.">".$value."</option>";
		}
	}
}